package com.swq.java.code.chapter19.code17;

import javax.swing.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class AdapterDemo extends JFrame {
    private JDialog dialog;
    private JLabel label;

    public AdapterDemo(String title) {
        super(title);

        dialog = new JDialog(this, "Note", true);
        label = new JLabel();
        dialog.add(label);
        dialog.setSize(100, 100);


        dialog.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                dialog.setVisible(false);  //隐藏会话框
            }
        });

        requestFocus();  //使JFrame能够接收用户的键盘输入

        addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent ev) {
                char key = ev.getKeyChar();
                label.setText("用户选择的键为: " + key);
                System.out.println("Key adapter");
                dialog.setVisible(true);  //显示会话框
            }
        });

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                System.exit(0);  //结束程序
            }
        });

        setSize(300, 300);
        setVisible(true);
    }

    public static void main(String args[]) {
        new AdapterDemo("Hello");
    }
}
